<template>
  <el-form :model="form" :rules="rules" ref="loginForm" class="login-form">
    <div class="header">
      <el-button
        @click="toggleTitle('登录')"
        v-if="title == '注册'"
        size="small"
        type="primary"
        icon="Back"
        text
        bg
      />
      <h3 class="title">{{ title }}</h3>
    </div>
    <el-form-item prop="username">
      <el-input
        @keyup.enter.native="apiMethod"
        v-model="form.username"
        placeholder="账号"
        clearable
      ></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model.trim="form.password"
        type="password"
        placeholder="密码"
        show-password
        clearable
        @keyup.enter.native="apiMethod"
      ></el-input>
    </el-form-item>
    <div v-if="title == '登录'" class="NoAccount">
      没有账号？<el-link type="primary" @click="toggleTitle('注册')"
        >去注册</el-link
      >
    </div>
    <el-form-item>
      <el-button
        v-loading="loading"
        :loading-icon="Loading"
        class="btn"
        type="primary"
        @click="apiMethod"
        >{{ title }}</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { useRouter } from "vue-router";
import { login_api, register_api } from "@/api/user/index";
import { Loading } from "@element-plus/icons-vue";

const router = useRouter();
const loginForm = ref();
const loading = ref(false);
const title = ref("登录");
const formData = {
  // username: "admin",
  // password: "admin123",
  username: "",
  password: "",
};
const form = reactive({ ...formData });
const initForm = () => {
  Object.assign(form, formData);
};

const rules = reactive({
  username: [{ required: true, message: "账号不能为空", trigger: "blur" }],
  password: [{ required: true, message: "密码不能为空", trigger: "blur" }],
});
const apiMethod = useDebounceFn(() => {
  loading.value = true;
  submitForm();
}, 1000);

const submitForm = () => {
  loginForm.value?.validate(async (valid: any) => {
    if (valid) {
      // 这里可以添加登录逻辑，例如发送登录请求
      let res: any = null;
      try {
        if (title.value == "登录") {
          res = await login_api(form);
        } else {
          res = await register_api(form);
        }
      } catch (err) {
        ElMessage({
          type: "error",
          message: "服务器错误",
        });
        loading.value = false;
      }
      // console.log('res', res)

      if (res?.code == 0) {
        ElMessage({
          type: "success",
          message: res.msg,
        });
        localStorage.setItem("accessToken", res.data.token);
        localStorage.setItem("userData", JSON.stringify(res.data.userData));
        router.push({ path: "/", query: { category: "all" } });
      } else {
        ElMessage({
          type: "error",
          message: res.msg,
        });
      }
      loading.value = false;
    } else {
      ElMessage?.error("请检查你所填项");
    }
  });
};
const toggleTitle = (str?: string) => {
  title.value = str;
  initForm();
  loginForm.value.clearValidate();
};
watch(
  form,
  (val: any) => {
    // console.log("val",val);

    // 去除空格
    form.username = form.username.replace(/\s+/g, "");
    form.password = form.password.replace(/\s+/g, "");
  },
  { deep: true }
);
</script>

<style lang="scss" scoped>
.login-form {
  width: 300px;
  margin: 0 auto;
  padding: 20px;
  border-radius: 5px;
  box-shadow: var(--el-box-shadow);
}
.btn {
  width: 100%;
}
.title {
  width: 100%;
  text-align: center;
  margin: 0;
}

.NoAccount {
  font-size: 12px;
  margin: 0;
  margin-bottom: 10px;
  text-align: right;
}
.header {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
  position: relative;
  .el-button {
    position: absolute;
    top: 50%;
    left: 0;
    transform: translateY(-50%);
  }
}
</style>

function ElMessage(arg0: { type: string; message: any }) { throw new
Error('Function not implemented.') } function ElMessage(arg0: { type: string;
message: any }) { throw new Error('Function not implemented.') }
